/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BrowseKB.java
 *
 * Created on 15/07/2010, 12:44:37 PM
 */

package utilities;

import com.hp.hpl.jena.ontology.OntModel;
import edu.stanford.smi.protege.model.KnowledgeBase;
import edu.stanford.smi.protege.model.Project;
import edu.stanford.smi.protegex.owl.model.OWLModel;
import java.net.URI;
import java.util.*;
import java.util.logging.*;
import java.io.*;

import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.util.*;


import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.dom4j.*;
import org.dom4j.io.*;


import com.hp.hpl.jena.query.*;
import com.hp.hpl.jena.rdf.arp.impl.Location;

import com.hp.hpl.jena.util.FileUtils;
import edu.stanford.smi.protege.model.*;
import edu.stanford.smi.protege.widget.*;
import edu.stanford.smi.protege.resource.*;

import edu.stanford.smi.protege.exception.OntologyLoadException;
import edu.stanford.smi.protege.model.KnowledgeBaseFactory;
import edu.stanford.smi.protegex.owl.model.OWLModel;
import edu.stanford.smi.protegex.owl.model.OWLNamedClass;
import edu.stanford.smi.protegex.owl.ProtegeOWL;
import edu.stanford.smi.protegex.owl.jena.JenaOWLModel;
import edu.stanford.smi.protegex.owl.model.OWLDatatypeProperty;
import edu.stanford.smi.protegex.owl.model.OWLObjectProperty;
import edu.stanford.smi.protegex.owl.model.RDFIndividual;
import edu.stanford.smi.protegex.owl.model.query.QueryResults;
import javax.swing.table.DefaultTableModel;
import jess.*;

/**
 *
 * @author ATuan
 */
public class BrowseKB extends javax.swing.JDialog {

    /** Creates new form BrowseKB */
    public BrowseKB(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        try{
        formatterTxt = new SimpleFormatter();
        //formatterTxt = new XMLFormatter();
        fileTxt = new FileHandler("BrowseKBLog.log",true);
        fileTxt.setFormatter(formatterTxt);
        theLogger.addHandler(fileTxt);
        }catch(Exception e){
            theLogger.severe(e.toString());
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        ConnectKnowledgeBaseBtn = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        DBURLtxtFld = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        SparqlTxtArea = new javax.swing.JTextArea();
        SparqlBtn = new javax.swing.JButton();
        DBPasswordTxtFld = new javax.swing.JPasswordField();
        jTextField2 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        DBusernameTxtFld = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        DeleteAllBtn = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        instanceNameTxtFld = new javax.swing.JTextField();
        DeleteInstanceBtn = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        LoadInstanceBtn = new javax.swing.JButton();
        list1 = new java.awt.List();
        NextBtn = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        ImportGPStoKBbtn = new javax.swing.JButton();
        AddOneInstanceBtn = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        list2 = new java.awt.List();
        JessTestBtn = new javax.swing.JButton();
        GetSparqlResultBtn = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        JessRuleArea = new javax.swing.JTextArea();
        JessStringTF = new javax.swing.JTextField();
        AssertAvgSpeedBtn = new javax.swing.JButton();
        SpeedLimitTF = new javax.swing.JTextField();
        avgSpeedTF = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        ImportRawContextToKB = new javax.swing.JButton();
        CreateSinglePlaceBtn = new javax.swing.JButton();
        latTF = new javax.swing.JTextField();
        lonTF = new javax.swing.JTextField();
        tsTF = new javax.swing.JTextField();
        CreateSingleLocationBtn = new javax.swing.JButton();
        InstanceNameTF = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        CheckExistedBtn = new javax.swing.JButton();
        jLabel11 = new javax.swing.JLabel();
        DurationTF = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        ProjectsTF = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        BasedDirTF = new javax.swing.JTextField();
        LoadProjectsBtn = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        DatasetFilenameTF = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        LoggingTA = new javax.swing.JTextArea();
        jLabel16 = new javax.swing.JLabel();
        ExitBtn = new javax.swing.JButton();
        GenerateFromPBVC0Btn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(placecommframework.PlaceCommFrameworkApp.class).getContext().getResourceMap(BrowseKB.class);
        ConnectKnowledgeBaseBtn.setText(resourceMap.getString("ConnectKnowledgeBaseBtn.text")); // NOI18N
        ConnectKnowledgeBaseBtn.setName("ConnectKnowledgeBaseBtn"); // NOI18N
        ConnectKnowledgeBaseBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                ConnectKnowledgeBaseBtnMouseClicked(evt);
            }
        });

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        DBURLtxtFld.setText(resourceMap.getString("DBURLtxtFld.text")); // NOI18N
        DBURLtxtFld.setName("DBURLtxtFld"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        SparqlTxtArea.setColumns(20);
        SparqlTxtArea.setRows(5);
        SparqlTxtArea.setText(resourceMap.getString("SparqlTxtArea.text")); // NOI18N
        SparqlTxtArea.setName("SparqlTxtArea"); // NOI18N
        jScrollPane1.setViewportView(SparqlTxtArea);

        SparqlBtn.setText(resourceMap.getString("SparqlBtn.text")); // NOI18N
        SparqlBtn.setName("SparqlBtn"); // NOI18N
        SparqlBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                SparqlBtnMouseClicked(evt);
            }
        });

        DBPasswordTxtFld.setText(resourceMap.getString("DBPasswordTxtFld.text")); // NOI18N
        DBPasswordTxtFld.setName("DBPasswordTxtFld"); // NOI18N

        jTextField2.setText(resourceMap.getString("jTextField2.text")); // NOI18N
        jTextField2.setName("jTextField2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        DBusernameTxtFld.setText(resourceMap.getString("DBusernameTxtFld.text")); // NOI18N
        DBusernameTxtFld.setName("DBusernameTxtFld"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        DeleteAllBtn.setText(resourceMap.getString("DeleteAllBtn.text")); // NOI18N
        DeleteAllBtn.setName("DeleteAllBtn"); // NOI18N
        DeleteAllBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                DeleteAllBtnMouseClicked(evt);
            }
        });

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        instanceNameTxtFld.setText(resourceMap.getString("instanceNameTxtFld.text")); // NOI18N
        instanceNameTxtFld.setName("instanceNameTxtFld"); // NOI18N

        DeleteInstanceBtn.setText(resourceMap.getString("DeleteInstanceBtn.text")); // NOI18N
        DeleteInstanceBtn.setName("DeleteInstanceBtn"); // NOI18N
        DeleteInstanceBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                DeleteInstanceBtnMouseClicked(evt);
            }
        });

        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        LoadInstanceBtn.setText(resourceMap.getString("LoadInstanceBtn.text")); // NOI18N
        LoadInstanceBtn.setName("LoadInstanceBtn"); // NOI18N
        LoadInstanceBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                LoadInstanceBtnMouseClicked(evt);
            }
        });

        list1.setMultipleMode(true);
        list1.setName("list1"); // NOI18N
        list1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                list1ActionPerformed(evt);
            }
        });

        NextBtn.setText(resourceMap.getString("NextBtn.text")); // NOI18N
        NextBtn.setName("NextBtn"); // NOI18N
        NextBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                NextBtnMouseClicked(evt);
            }
        });

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N

        ImportGPStoKBbtn.setText(resourceMap.getString("ImportGPStoKBbtn.text")); // NOI18N
        ImportGPStoKBbtn.setName("ImportGPStoKBbtn"); // NOI18N
        ImportGPStoKBbtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                ImportGPStoKBbtnMouseClicked(evt);
            }
        });

        AddOneInstanceBtn.setText(resourceMap.getString("AddOneInstanceBtn.text")); // NOI18N
        AddOneInstanceBtn.setName("AddOneInstanceBtn"); // NOI18N
        AddOneInstanceBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                AddOneInstanceBtnMouseClicked(evt);
            }
        });

        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton3MouseClicked(evt);
            }
        });

        list2.setMultipleMode(true);
        list2.setName("list2"); // NOI18N
        list2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                list2ActionPerformed(evt);
            }
        });

        JessTestBtn.setText(resourceMap.getString("JessTestBtn.text")); // NOI18N
        JessTestBtn.setName("JessTestBtn"); // NOI18N
        JessTestBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                JessTestBtnMouseClicked(evt);
            }
        });

        GetSparqlResultBtn.setText(resourceMap.getString("GetSparqlResultBtn.text")); // NOI18N
        GetSparqlResultBtn.setName("GetSparqlResultBtn"); // NOI18N
        GetSparqlResultBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                GetSparqlResultBtnMouseClicked(evt);
            }
        });

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        JessRuleArea.setColumns(20);
        JessRuleArea.setRows(5);
        JessRuleArea.setText(resourceMap.getString("JessRuleArea.text")); // NOI18N
        JessRuleArea.setName("JessRuleArea"); // NOI18N
        jScrollPane3.setViewportView(JessRuleArea);

        JessStringTF.setText(resourceMap.getString("JessStringTF.text")); // NOI18N
        JessStringTF.setName("JessStringTF"); // NOI18N

        AssertAvgSpeedBtn.setText(resourceMap.getString("AssertAvgSpeedBtn.text")); // NOI18N
        AssertAvgSpeedBtn.setName("AssertAvgSpeedBtn"); // NOI18N
        AssertAvgSpeedBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                AssertAvgSpeedBtnMouseClicked(evt);
            }
        });

        SpeedLimitTF.setText(resourceMap.getString("SpeedLimitTF.text")); // NOI18N
        SpeedLimitTF.setName("SpeedLimitTF"); // NOI18N

        avgSpeedTF.setText(resourceMap.getString("avgSpeedTF.text")); // NOI18N
        avgSpeedTF.setName("avgSpeedTF"); // NOI18N

        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N

        jLabel8.setText(resourceMap.getString("jLabel8.text")); // NOI18N
        jLabel8.setName("jLabel8"); // NOI18N

        jLabel9.setText(resourceMap.getString("jLabel9.text")); // NOI18N
        jLabel9.setName("jLabel9"); // NOI18N

        ImportRawContextToKB.setText(resourceMap.getString("ImportRawContextToKB.text")); // NOI18N
        ImportRawContextToKB.setName("ImportRawContextToKB"); // NOI18N
        ImportRawContextToKB.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                ImportRawContextToKBMouseClicked(evt);
            }
        });

        CreateSinglePlaceBtn.setText(resourceMap.getString("CreateSinglePlaceBtn.text")); // NOI18N
        CreateSinglePlaceBtn.setName("CreateSinglePlaceBtn"); // NOI18N
        CreateSinglePlaceBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                CreateSinglePlaceBtnMouseClicked(evt);
            }
        });

        latTF.setText(resourceMap.getString("latTF.text")); // NOI18N
        latTF.setName("latTF"); // NOI18N

        lonTF.setText(resourceMap.getString("lonTF.text")); // NOI18N
        lonTF.setName("lonTF"); // NOI18N

        tsTF.setText(resourceMap.getString("tsTF.text")); // NOI18N
        tsTF.setName("tsTF"); // NOI18N

        CreateSingleLocationBtn.setText(resourceMap.getString("CreateSingleLocationBtn.text")); // NOI18N
        CreateSingleLocationBtn.setName("CreateSingleLocationBtn"); // NOI18N

        InstanceNameTF.setText(resourceMap.getString("InstanceNameTF.text")); // NOI18N
        InstanceNameTF.setName("InstanceNameTF"); // NOI18N

        jLabel10.setName("jLabel10"); // NOI18N

        CheckExistedBtn.setText(resourceMap.getString("CheckExistedBtn.text")); // NOI18N
        CheckExistedBtn.setName("CheckExistedBtn"); // NOI18N
        CheckExistedBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                CheckExistedBtnMouseClicked(evt);
            }
        });

        jLabel11.setText(resourceMap.getString("jLabel11.text")); // NOI18N
        jLabel11.setName("jLabel11"); // NOI18N

        DurationTF.setText(resourceMap.getString("DurationTF.text")); // NOI18N
        DurationTF.setName("DurationTF"); // NOI18N

        jLabel12.setText(resourceMap.getString("jLabel12.text")); // NOI18N
        jLabel12.setName("jLabel12"); // NOI18N

        ProjectsTF.setText(resourceMap.getString("ProjectsTF.text")); // NOI18N
        ProjectsTF.setName("ProjectsTF"); // NOI18N

        jLabel13.setText(resourceMap.getString("jLabel13.text")); // NOI18N
        jLabel13.setName("jLabel13"); // NOI18N

        jLabel14.setText(resourceMap.getString("jLabel14.text")); // NOI18N
        jLabel14.setName("jLabel14"); // NOI18N

        BasedDirTF.setText(resourceMap.getString("BasedDirTF.text")); // NOI18N
        BasedDirTF.setName("BasedDirTF"); // NOI18N

        LoadProjectsBtn.setText(resourceMap.getString("LoadProjectsBtn.text")); // NOI18N
        LoadProjectsBtn.setName("LoadProjectsBtn"); // NOI18N
        LoadProjectsBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                LoadProjectsBtnMouseClicked(evt);
            }
        });

        jButton4.setText(resourceMap.getString("jButton4.text")); // NOI18N
        jButton4.setName("jButton4"); // NOI18N

        DatasetFilenameTF.setText(resourceMap.getString("DatasetFilenameTF.text")); // NOI18N
        DatasetFilenameTF.setName("DatasetFilenameTF"); // NOI18N

        jLabel15.setText(resourceMap.getString("jLabel15.text")); // NOI18N
        jLabel15.setName("jLabel15"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        LoggingTA.setColumns(20);
        LoggingTA.setRows(5);
        LoggingTA.setName("LoggingTA"); // NOI18N
        jScrollPane2.setViewportView(LoggingTA);

        jLabel16.setText(resourceMap.getString("jLabel16.text")); // NOI18N
        jLabel16.setName("jLabel16"); // NOI18N

        ExitBtn.setText(resourceMap.getString("ExitBtn.text")); // NOI18N
        ExitBtn.setName("ExitBtn"); // NOI18N
        ExitBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                ExitBtnMouseClicked(evt);
            }
        });

        GenerateFromPBVC0Btn.setText(resourceMap.getString("GenerateFromPBVC0Btn.text")); // NOI18N
        GenerateFromPBVC0Btn.setName("GenerateFromPBVC0Btn"); // NOI18N
        GenerateFromPBVC0Btn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                GenerateFromPBVC0BtnMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(instanceNameTxtFld, javax.swing.GroupLayout.DEFAULT_SIZE, 761, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel3)
                .addGap(6, 6, 6)
                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel11)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(DurationTF, javax.swing.GroupLayout.DEFAULT_SIZE, 490, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ImportRawContextToKB)
                .addGap(48, 48, 48))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(DBusernameTxtFld, javax.swing.GroupLayout.DEFAULT_SIZE, 755, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(DBURLtxtFld, javax.swing.GroupLayout.DEFAULT_SIZE, 785, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(ConnectKnowledgeBaseBtn)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(SparqlBtn, javax.swing.GroupLayout.DEFAULT_SIZE, 728, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 692, Short.MAX_VALUE)
                .addComponent(DBPasswordTxtFld, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 807, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel6)
                .addGap(18, 18, 18)
                .addComponent(DeleteInstanceBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(DeleteAllBtn)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(LoadInstanceBtn)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(NextBtn)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ImportGPStoKBbtn)
                .addContainerGap(278, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(list1, javax.swing.GroupLayout.DEFAULT_SIZE, 797, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(list2, javax.swing.GroupLayout.DEFAULT_SIZE, 797, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(JessTestBtn)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(AssertAvgSpeedBtn)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(avgSpeedTF, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(SpeedLimitTF, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(JessStringTF, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 797, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(AddOneInstanceBtn)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(GetSparqlResultBtn)
                .addContainerGap(288, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel10)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(InstanceNameTF))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(CreateSinglePlaceBtn)
                        .addGap(153, 153, 153)
                        .addComponent(latTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lonTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(tsTF, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(CreateSingleLocationBtn))
                    .addComponent(CheckExistedBtn))
                .addContainerGap(145, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel12)
                .addContainerGap(719, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jLabel15, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(DatasetFilenameTF)
                    .addComponent(BasedDirTF))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel13)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(ProjectsTF, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(LoadProjectsBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ExitBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(GenerateFromPBVC0Btn)))
                .addContainerGap(135, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 542, Short.MAX_VALUE)
                .addGap(265, 265, 265))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel16)
                .addContainerGap(720, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(DBURLtxtFld, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(4, 4, 4)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(DBusernameTxtFld, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(DBPasswordTxtFld, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ConnectKnowledgeBaseBtn)
                    .addComponent(SparqlBtn))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(ImportRawContextToKB)
                        .addComponent(jLabel11)
                        .addComponent(DurationTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(instanceNameTxtFld, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(DeleteInstanceBtn)
                    .addComponent(DeleteAllBtn)
                    .addComponent(LoadInstanceBtn)
                    .addComponent(NextBtn)
                    .addComponent(ImportGPStoKBbtn))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(list1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CreateSinglePlaceBtn)
                    .addComponent(latTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lonTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tsTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(CreateSingleLocationBtn))
                .addGap(1, 1, 1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(InstanceNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10)
                    .addComponent(CheckExistedBtn))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(AddOneInstanceBtn)
                    .addComponent(jButton3)
                    .addComponent(GetSparqlResultBtn))
                .addGap(5, 5, 5)
                .addComponent(list2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(JessTestBtn)
                    .addComponent(JessStringTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(AssertAvgSpeedBtn)
                    .addComponent(avgSpeedTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8)
                    .addComponent(jLabel9)
                    .addComponent(SpeedLimitTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addGap(30, 30, 30)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel12)
                .addGap(3, 3, 3)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel14)
                            .addComponent(BasedDirTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel13))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel15)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(DatasetFilenameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jButton4)
                                .addComponent(ExitBtn)
                                .addComponent(GenerateFromPBVC0Btn))))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(ProjectsTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(LoadProjectsBtn)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel16)
                .addGap(7, 7, 7)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(289, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void ConnectKnowledgeBaseBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ConnectKnowledgeBaseBtnMouseClicked

        try {
            // TODO add your handling code here:
            String className = "com.mysql.jdbc.Driver";
            Class.forName(className);
            DB_URL = DBURLtxtFld.getText();
            DB_USER =DBusernameTxtFld.getText();

            DB_PASSWD = DBPasswordTxtFld.getText();
            String DB = "MySQL"; // database type
            Collection errors = new ArrayList();

            
            Date d1=new Date();
            long l1=d1.getTime();
            prj = Project.loadProjectFromFile(instanceNameTxtFld.getText().trim(),errors);
            owlModel = (OWLModel) prj.getKnowledgeBase();
            kb  = prj.getKnowledgeBase();

            Date d2=new Date();
            long l2=d2.getTime();

            theLogger.info("Connected to MySQL in "+(l2-l1) +" ms");
            instanceNameTxtFld.setText("d:\\\\myphd\\\\gps.csv");

        } catch (ClassNotFoundException ex) {
            theLogger.severe(ex.toString());
        }
    }//GEN-LAST:event_ConnectKnowledgeBaseBtnMouseClicked

    private void DeleteAllBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_DeleteAllBtnMouseClicked
        // TODO add your handling code here:

        String sInstanceURI="";

      long lItemCount = list1.getItemCount();
     for (int i=0; i<lItemCount; i++){
        sInstanceURI=list1.getItem(i);
         try{
         Date d1=new Date();
         long lT1=d1.getTime();
         Instance insTemp= null;
         boolean getInst=false;
         try{
         insTemp= kb.getInstance(sInstanceURI);
         getInst=true;
         }catch (Exception e){
             System.out.println("Get instance failed");
           theLogger.severe("Get instance failed");
         }
         if (getInst) {
         kb.deleteInstance(insTemp);
         }
         Date d2=new Date();
         long lT2=d2.getTime();
         theLogger.info("Delete 1 instance for "+(lT2-lT1)+" ms");
         theLogger.info("Instance "+ sInstanceURI +" deleted");

         }catch(Exception ex){
             System.out.println("Delete failed");
             theLogger.severe(ex.toString());
         }
     }// End for
     
    }//GEN-LAST:event_DeleteAllBtnMouseClicked
    public void ResultToFact( QueryResults results ){
        try {
            String sRule = "(deffunction traffic (?avgSpeed ?speedLimit) " +
                    "(if (and(<= ?avgSpeed (* 0.3 ?speedLimit)) " + "       " +
                    " (> ?avgSpeed 0)) then " + "     ( printout t \"Traffic JAM\" crlf)) " +
                    " else (if (and (<= ?avgSpeed (* 0.5 ?speedLimit)) " +
                    "          (> ?avgSpeed (* 0.3 ?speedLimit))) then  " +
                    "          (printout t \"Very Heavy\" crlf)) " +
                    " else (if (and (<= ?avgSpeed (* 0.7  ?speedLimit)) " +
                    "      (> ?avgSpeed  (* 0.5 ?speedLimit)) )  then " +
                    "      (printout t \"Heavy\" crlf)) " +
                    "  else (if (and (<= ?avgSpeed ?speedLimit) " +
                    "       (> ?avgSpeed (* .70 ?speedLimit))) then " +
                    "       (printout t \"OK\" crlf)) " +
                    "   else (if (> ?avgSpeed ?speedLimit) then " +
                    "         (printout t \"Over speeding\" crlf)))";
            Rete engine = new Rete();
            Value v = engine.eval(sRule);

            Fact f = v.factValue(engine.getGlobalContext());
        } catch (JessException ex) {
            Logger.getLogger(BrowseKB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private void SPARQL2JessFact(QueryResults results){



    }
    private void SparqlBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_SparqlBtnMouseClicked
        try {
            int iii=0;
            String sQuery=SparqlTxtArea.getText();
            Date d1=new Date();
            QueryResults results = owlModel.executeSPARQLQuery(sQuery);
            Date d2=new Date();
            List l=results.getVariables();

            Iterator iter=l.iterator();
            while (iter.hasNext()){
                System.out.println("SPARQL variables: "+iter.next().toString());
            }
            
            
            long lTimeExecutingQuery=d2.getTime()-d1.getTime();
            theLogger.info("Time for SPARQL:"+sQuery+"="+lTimeExecutingQuery+" ms");
            DurationTF.setText("Duration: "+lTimeExecutingQuery+"ms");

            //ResultToFact(results);
            float fSpeedSum=0.0f;

            ///////////////////////////////////////////////////

            try {
        FileOutputStream out; // declare a file output object
        PrintStream p; // declare a print stream object

            out = new FileOutputStream("n:\\temp\\sparqlQueryResult.txt",true);
            // Connect print stream to the output stream
            p = new PrintStream( out );

            ///////////////////////////////////////////////////


            while (results.hasNext()){
                iii++;
             String sResult=results.next().toString();
             sResult.replaceAll("{","");
             sResult.replaceAll("}","");
             //System.out.println(sResult);
             p.println (sResult);
            //p.println ("Inet Address: "+socket.getInetAddress().toString());

             //theLogger.info(sResult);
             String [] sVal=sResult.split(",");
             int iSizeOfsVal=sVal.length;
           //  System.out.println("iSizeOfsVal="+iSizeOfsVal);
             
             if (iSizeOfsVal>1) {
             String sSpeed=sVal[0];
             float fSpeed=Float.valueOf(sSpeed.substring(7));
             fSpeedSum=fSpeedSum+fSpeed;
             }
             
             else {
                 String sSpeed=sResult;
                 //
                 String [] sValue=sSpeed.split("=");
                float   fSpeed=Float.valueOf(sValue[1].substring(0, sValue[1].length()));
                  fSpeedSum=fSpeedSum+fSpeed;
             }
            // System.out.println("Speed="+fSpeed);

             //int iSize=sVal.length;
               //for (int i=0; i<iSize; i++)      {
                 //System.out.print("var"+i+": "+sVal[i].trim()+",");
               //}
             //System.out.println("\n") ;
             }// End while 

         p.close();
        }
        catch (Exception ioe) {
            System.out.println("File error:"+ioe.toString());
        }
             theLogger.info("Query return: "+iii+" results");

            sAvg=fSpeedSum/iii;
            avgSpeedTF.setText(Float.toString(sAvg));
            SpeedLimitTF.setText("100");
            

             System.out.println("Average Speed="+sAvg);
             System.out.println("Done!!!");
        } catch (Exception ex) {
         theLogger.severe(ex.toString());
        }
    }//GEN-LAST:event_SparqlBtnMouseClicked
    public String ParseSparqlResult(String sKey){
        String s="";

        return s;
    }
      public static String [] ReverseGeocoding (String lat, String lon){
        String [] results=new String[5];
        try {
            //http://maps.google.com/maps/api/geocode/xml?latlng=-37.781094,145.02954&sensor=false
            String url = "http://maps.google.com/maps/api/geocode/xml?latlng=" + lat + "," + lon + "&sensor=false";
            HttpClient client = new HttpClient();
            GetMethod get = new GetMethod(url);
            int statusCode = client.executeMethod(get);
            if (statusCode != HttpStatus.SC_OK) {
                throw new RuntimeException(" Could not make HTTP  request properly: " + get.getStatusLine());
            }
            InputStream response = get.getResponseBodyAsStream();
            SAXReader reader = new SAXReader();
            Document document = reader.read(response);
            List list=document.selectNodes("//result");
            Iterator iter=list.iterator();
            while(iter.hasNext()){
                Element element=(Element)iter.next();
                Iterator iterator=element.elementIterator("formatted_address");
                while (iterator.hasNext()){
                    Element formattedAddressElement=(Element)iterator.next();
                    //System.out.println(formattedAddressElement.getText().trim());
                }
            }

            list = document.selectNodes("//result/address_component" );
            iter=list.iterator();
            String street_number="",route="", suburb="", postcode="", country="";
             while(iter.hasNext()){
             Element element=(Element)iter.next();

             //System.out.println("lAtributes:"+lAtributes+" lAtributes1: "+lAtributes1+" lAtributes2: "+lAtributes2);
             //System.out.println("Atribute Count:"+element.attributeCount());
             //Iterator iterator=element.elementIterator("long_name");
             String sLongname=element.elementText("long_name");
             String sType=element.elementText("type");

             if (sType.equals("street_number")){
                 if (sLongname.length()>0) street_number=sLongname;
                //System.out.println("Route name:"+route);
             }else if (sType.equals("route")){
                 if (sLongname.length()>0) route=sLongname;
                //System.out.println("Route name:"+route);
             }else if (sType.equals("postal_code")){
                 if (sLongname.length()>0) postcode=sLongname;
                 //System.out.println("post code:"+postcode);
             }else if (sType.equals("locality")){
                 if (sLongname.length()>0) suburb=sLongname;
                 //System.out.println("locality:"+suburb);
             }else if (sType.equals("country")){
                 if (sLongname.length()>0) country=sLongname;
                 //System.out.println("locality:"+suburb);
             }
              //while(iterator.hasNext()){
              //Element longElement=(Element)iterator.next();
              //System.out.println(longElement.getText().trim());
              //}
             }
             results[0]=street_number;
             results[1]=route;
             results[2]=suburb;
             results[3]=postcode;
             results[4]=country;
            //System.out.println("Number:"+street_number+", route:"+route+
                    //", suburb:"+suburb+", postcode:"+postcode+", country:"+country);

        } catch (DocumentException ex) {
            
        } catch (IOException ex) {
            
        }
        return results;
    }

    private void DeleteInstanceBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_DeleteInstanceBtnMouseClicked
        // TODO add your handling code here:
   

    }//GEN-LAST:event_DeleteInstanceBtnMouseClicked

    private void LoadInstanceBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_LoadInstanceBtnMouseClicked
        // TODO add your handling code here:
String sFileName=instanceNameTxtFld.getText().trim();
         try{
    // Open the file that is the first
    // command line parameter
    FileInputStream fstream = new FileInputStream(sFileName);
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
        
        list1.add(strLine.trim());

    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
        


    }//GEN-LAST:event_LoadInstanceBtnMouseClicked

    private void list1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_list1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_list1ActionPerformed

    private void NextBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_NextBtnMouseClicked
        // TODO add your handling code here:
        String sInstanceURI=list1.getItem(iPos).trim();
        iPos++;

     try{
     Date d1=new Date();
     long lT1=d1.getTime();
     Instance insTemp= null;
     boolean getInst=false;
     try{
     insTemp= kb.getInstance(sInstanceURI);
     System.out.println("Instance: "+insTemp.toString());
     getInst=true;
     }catch (Exception e){
         System.out.println("Get instance failed");
       theLogger.severe("Get instance failed");
     }
     theLogger.info(insTemp.toString());

     if (getInst) {
     kb.deleteInstance(insTemp);
     }

     Date d2=new Date();
     long lT2=d2.getTime();
     theLogger.info("Delete 1 instance for "+(lT2-lT1)+" ms");
     theLogger.info("Instance "+ sInstanceURI +" deleted");

     }catch(Exception ex){
         System.out.println("Delete failed");
         theLogger.severe(ex.toString());
     }


    }//GEN-LAST:event_NextBtnMouseClicked

    private void ImportGPStoKBbtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ImportGPStoKBbtnMouseClicked
        // TODO add your handling code here:

    try{
    // Open the file that is the first
    // command line parameter
    String sFilename=instanceNameTxtFld.getText().trim();

    
    FileInputStream fstream = new FileInputStream(sFilename);
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    // Pattern
    //A:001ADCD54B7C,N:www.tuannguyen.mobi,T:Sat Oct 03 15:03:08 GMT+10:00 2009,
    //D:1254546188143,S:2.8888700008392334,Lat:-37.751601666666666,Lon:145.049495,
    //Alt:59.15999984741211
    String sNextLine="";
    while ((strLine = br.readLine().trim()) != null)   {
      // Print the content on the console
      list2.add(strLine);
      
      String [] s=strLine.split(",");
      String sBTAddress=s[0].substring(2);
      String sBTName=s[1].substring(2);
      String sDate=s[2].substring(2);
      String sTimestamp=s[3].substring(2);
      String sSpeed=s[4].substring(2);
      String sLat=s[5].substring(4);
      String sLon=s[6].substring(4);
      String sAlt=s[7].substring(4);

      try {
          sNextLine=br.readLine().trim();
      }catch (Exception e){
          theLogger.severe("End of input");
          sNextLine=null;
      }

      if ( sNextLine !=null) {
         // System.out.println("Read next line ");
          String [] sNext=sNextLine.split(",");
          String sLatNext=sNext[5].substring(4);
          String sLonNext=sNext[6].substring(4);
          // skip if location has not change
          if ((sLat.equals(sLatNext))&&(sLon.equals(sLonNext))){             
             System.out.println("Skip this line because the same value");
          }else {
              float fLat=Float.valueOf(sLat);
              float fLon=Float.valueOf(sLon);
              float fAlt=Float.valueOf(sAlt);
              float fSpeed=Float.valueOf(sSpeed);
              String sURI=DBURLtxtFld.getText().trim();

              // Create new Location;
              InsertInstance(fLat,fLon,fAlt,fSpeed,sDate,sTimestamp,sBTAddress,sBTName,sURI);
              theLogger.info("Instance created success0fully");
              

          }
      }
    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }


    }//GEN-LAST:event_ImportGPStoKBbtnMouseClicked

    

    private void AddOneInstanceBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AddOneInstanceBtnMouseClicked
        // TODO add your handling code here:
        InsertInstance(1.00f,1.00f,1.00f,99.90f,"t1","t2","","","");
    }//GEN-LAST:event_AddOneInstanceBtnMouseClicked

    private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked
        // TODO add your handling code here:
      String strLine="A:001ADCD54B7C,N:www.tuannguyen.mobi,T:Sat Oct 03 15:03:08 GMT+10:00 2009,D:1254546188143,S:2.8888700008392334,Lat:-37.751601666666666,Lon:145.049495,Alt:59.15999984741211";

      System.out.println (strLine);
      strLine.trim();
      String [] s=strLine.split(",");
      String sBTAddress=s[0].substring(2);
      String sBTName=s[1].substring(2);
      String sDate=s[2].substring(2);
      String sTimestamp=s[3].substring(2);
      String sSpeed=s[4].substring(2);
      String sLat=s[5].substring(4);
      String sLon=s[6].substring(4);
      String sAlt=s[7].substring(4);
      System.out.println( sBTAddress+" "+sBTName+" "+sDate+" "+sTimestamp+" "+ sSpeed+" "+ sLat+" "+
                      sLon+" "+sAlt);
    }//GEN-LAST:event_jButton3MouseClicked

    private void list2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_list2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_list2ActionPerformed

    private void JessTestBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JessTestBtnMouseClicked
        try {
            // TODO add your handling code here:
            Rete engine = new Rete();
            

            String s1=JessRuleArea.getText().trim();
            engine.eval(s1);

            String sSpeed=avgSpeedTF.getText().trim();
            String sSpeedLimit=SpeedLimitTF.getText().trim();
            
            String callFunction= "(traffic "+sSpeed+" "+sSpeedLimit+")";
            Value v = engine.eval(callFunction);
            JessStringTF.setText(v.toString());
            theLogger.info("Jess rule evaluated");
            
        } catch (JessException ex) {
            Logger.getLogger(BrowseKB.class.getName()).log(Level.SEVERE, null, ex);
        }



    }//GEN-LAST:event_JessTestBtnMouseClicked

    private void GetSparqlResultBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_GetSparqlResultBtnMouseClicked
        // TODO add your handling code here:
        //String s="select ?asdf ?asdf ?asdfasd where asdfa sdfas dfa sdfa sdf ";
        
        String sSPARQL=SparqlTxtArea.getText().toLowerCase().trim();
        int iWhere=sSPARQL.indexOf("where");
        String sVariables=sSPARQL.substring(7,iWhere).trim().replace('?', '%');
        //list2.add(sVariables);
        String []sVal=sVariables.split("%");
        for (int i=0; i<sVal.length ; i++){
            list2.add(sVal[i].trim());
        }        
    }//GEN-LAST:event_GetSparqlResultBtnMouseClicked

    private void AssertAvgSpeedBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AssertAvgSpeedBtnMouseClicked
        // TODO add your handling code here:
        //(assert (numbers 2 2))
        String sAvgSpeed=SpeedLimitTF.getText().trim();
        String sSpeedLimit=avgSpeedTF.getText().trim();
        String s="(bind ?avgSpeed "+ sAvgSpeed+")(bind ?speedLimit "+sSpeedLimit+")";
        JessStringTF.setText(s);
    }//GEN-LAST:event_AssertAvgSpeedBtnMouseClicked

    private void ImportRawContextToKBMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ImportRawContextToKBMouseClicked

    try{

    String sFilename=instanceNameTxtFld.getText().trim();
    FileInputStream fstream = new FileInputStream(sFilename);
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    long lDuration=0, lCount=0;
    Date d1=new Date();
    long lT1=d1.getTime();
    while ((strLine = br.readLine().trim()) != null)   {
      // Print the content on the console
      list2.add(strLine);

      String [] s=strLine.split(",");
      String sBTAddress=s[0].substring(2);
      String sBTName=s[1].substring(2);
      String sDate=s[2].substring(2);
      String sTimestamp=s[3].substring(2);
      String sSpeed=s[4].substring(2);
      String sLat=s[5].substring(4);
      String sLon=s[6].substring(4);
      String sAlt=s[7].substring(4);
      try{
          float fLat=Float.valueOf(sLat);
          float fLon=Float.valueOf(sLon);
          float fAlt=Float.valueOf(sAlt);
          float fSpeed=Float.valueOf(sSpeed);
          String sURI=DBURLtxtFld.getText().trim();
          InsertInstance(fLat,fLon,fAlt,fSpeed,sDate,sTimestamp,sBTAddress,sBTName,sURI);
          lCount++;
          if ((lCount % 100) ==0){
              theLogger.info("100 instances inserted"); 
          }
      }catch (Exception ex1){
              theLogger.severe("Error converting string to float: "+ex1.toString());
      }
    }
    Date d2=new Date();
    long lT2=d2.getTime();

    lDuration= lT2 - lT1 ;
    theLogger.info("Insert "+lCount+" instances in "+lDuration+
            " ms, average "+(lDuration/lCount)+"ms/instance");

    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }

    }//GEN-LAST:event_ImportRawContextToKBMouseClicked

    private void CreateSinglePlaceBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CreateSinglePlaceBtnMouseClicked
        // TODO add your handling code here:
        String sURI=DBURLtxtFld.getText();
        String lat=latTF.getText().trim();
        String lon=lonTF.getText().trim();
        String sTimestamp=tsTF.getText().trim();
        
        CreatePlaceByReverseGeocoding ( sURI, lat, lon, sTimestamp);

    }//GEN-LAST:event_CreateSinglePlaceBtnMouseClicked

    private void CheckExistedBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CheckExistedBtnMouseClicked
        // TODO add your handling code here:
        
 Instance myInstance=null;
        try {
         myInstance= kb.getInstance(InstanceNameTF.getText().trim());
            if (myInstance.isValid()){
               theLogger.info("Instance is Valid");
            }
         System.out.println(myInstance.getName());
        }catch(Exception e){
            theLogger.info("Instance Does NOT Valid");
        }

        
    }//GEN-LAST:event_CheckExistedBtnMouseClicked

    private void LoadProjectsBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_LoadProjectsBtnMouseClicked
        // TODO add your handling code here:
        // TODO add your handling code here:
        String sProjects=ProjectsTF.getText();
        String [] projectList=sProjects.split(";");
        int iProjectLength=projectList.length;
        String sBasedDir=BasedDirTF.getText();
        String sPrjName="";
        Project prjTemp=null;
        theLogger.info("Load multiple projects ");
        long lNumberOfWillBeGenerated=0;
        String sDataSetFilename =DatasetFilenameTF.getText().trim();
        try{
            for (int i=0; i<iProjectLength; i++){
                sPrjName=projectList[i];
                projectList[i]=sBasedDir+sPrjName;
                // New Thread
                
                if (i==0){
                    lNumberOfWillBeGenerated=0;
                }else {
                    lNumberOfWillBeGenerated=lNumberOfWillBeGenerated+100000;
                }
                try {
                String sURI="http://www.tuannguyen.mobi/ontologies/2010/tinypbvc.owl#";
                theLogger.info("lNumberOfWillBeGenerated:"+lNumberOfWillBeGenerated);

                Collection errors = new ArrayList();
                Date d1=new Date();
                long l1=d1.getTime();
                
                GenerateDataToKB thrClass= new GenerateDataToKB(sBasedDir, sPrjName, sURI,
                        sDataSetFilename,  lNumberOfWillBeGenerated);
                Thread thr=new Thread(thrClass);
                threadClassList.add(thrClass) ;
                threadList.add(thr);
                thr.start();

                prjTemp=thrClass.getProject();
                prjList.add(prjTemp);
                kbList.add(prjTemp.getKnowledgeBase());
                owlModelList.add((OWLModel)prjTemp.getKnowledgeBase());

                Date d2=new Date();
                long l2=d2.getTime();
                theLogger.info("Project: "+projectList[i]+" is loaded in "+(l2-l1) +" ms");
                theLogger.info("Thread :"+sURI+" started");

                }catch(Exception e){
                    theLogger.severe("Load project: "+sBasedDir+sPrjName+" failed:"+e.toString());
                }


            }
        }catch(Exception e){
           theLogger.severe(" Failed to Connected to MySQL");
        }


    }//GEN-LAST:event_LoadProjectsBtnMouseClicked



    private void ExitBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ExitBtnMouseClicked
        // TODO add your handling code here:
        dispose();
        System.exit(0);
    }//GEN-LAST:event_ExitBtnMouseClicked

    private void GenerateFromPBVC0BtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_GenerateFromPBVC0BtnMouseClicked
       /*
         * The idea is Load p0.pprj
         * Traverse p0, get Location Instances and Postal Address
         * generate x*item of P0 then put to P1, P2,...P11
         *
         */
        
        long lNumberOfWillBeGenerated=0;
        String sURI="http://www.tuannguyen.mobi/ontologies/2010/tinypbvc.owl#";
        
        Project prj0  = myLoadProjectFromFile("n:\\1Working\\OntologyMySql\\p0.pprj");
        KnowledgeBase kb0=prj0.getKnowledgeBase();
        
        Project prj1  = myLoadProjectFromFile("n:\\1Working\\OntologyMySql\\p1.pprj");
        KnowledgeBase kb1=prj1.getKnowledgeBase();
         
        
        String sLocationClass=sURI+"Location";
        String sPostalAddressClass=sURI+"PostalAddress";

        Cls cLocClass=kb0.getCls(sLocationClass);
        Cls cPostAddrClass=kb0.getCls(sPostalAddressClass);

        Cls cLocClass1=kb1.getCls(sLocationClass);
        Cls cPostAddrClass1=kb1.getCls(sPostalAddressClass);

        Collection colLocationInstances=kb0.getInstances(cLocClass);
        Collection colPostalAddrInstances=kb0.getInstances(cPostAddrClass);
        Iterator iter =colLocationInstances.iterator();
        int iTimes=10;

         String sAlt=sURI+"alt";
            String sLat=sURI+"lat";
            String sLon=sURI+"lon";
            String sSpeed=sURI+"speed";
            String sTimestamp=sURI+"timestamp";
            String sDate=sURI+"date";

            String sPostalAddressName=sURI+"postalAddressName";
            String sPostCode =sURI+"postCode" ;
            String sStreetNumber=sURI+"streetNumber";
            String sStreetName=sURI+"streetName";
            String sSuburb=sURI+"suburb";
            String sCountry=sURI+"Country";


            Slot sAlt_slot=kb.getSlot(sAlt);
            Slot sLat_slot=kb.getSlot(sLat);
            Slot sLon_slot=kb.getSlot(sLon);
            Slot sSpeed_slot=kb.getSlot(sSpeed);
            Slot sTimestamp_slot=kb.getSlot(sTimestamp);
            Slot sDate_slot=kb.getSlot(sDate);

            Slot sPostalAddressName_slot=kb.getSlot(sPostalAddressName);
            Slot sPostCode_slot=kb.getSlot(sPostCode) ;
            Slot sStreetNumber_slot=kb.getSlot(sStreetNumber);
            Slot sStreetName_slot=kb.getSlot(sStreetName);
            Slot sSuburb_slot=kb.getSlot(sSuburb);
            Slot sCountry_slot=kb.getSlot(sCountry);

        while (iter.hasNext()){
            String sItem=iter.next().toString();
            String sLoc=sItem.substring(sItem.indexOf("(")+1,sItem.indexOf("of ["));
            System.out.println(sLoc);
           
            Instance tempoInstance=kb0.getInstance(sLoc);
           
            Instance tempPostalAddress=kb0.getInstance("Postal AdressInstance name");
            /*
            for (int i=0; i<iTimes;i++){
                //Duplicate instances
                 // Create new instance
                 instanceToAddTo = cPostalAddress.createDirectInstance(sInstanceName);
                 Slot streetNumber_slot  = kb.getSlot(streetNumberURI);
                 Slot streetName_slot  = kb.getSlot(streetNameURI);
                 Slot suburb_slot  = kb.getSlot(suburbURI);
                 Slot postCode_slot= kb.getSlot(postCodeURI);
                 Slot Country_slot = kb.getSlot(CountryURI);
                 Slot timestamp_slot = kb.getSlot(timestampURI);

                 instanceToAddTo.setOwnSlotValue(streetNumber_slot, streetNumberVal);
                 instanceToAddTo.setOwnSlotValue(streetName_slot,streetNameVal);
                 instanceToAddTo.setOwnSlotValue(suburb_slot,suburbVal);
                 instanceToAddTo.setOwnSlotValue(postCode_slot, postCodeVal);
                 instanceToAddTo.setOwnSlotValue(Country_slot,CountryVal);
                 instanceToAddTo.setOwnSlotValue(timestamp_slot, timestampVal);
                 kb.addInstance(instanceToAddTo, "Place: "+sInstanceName+" added", cPostalAddress, true);
            
            }

             */

         
        }

    }//GEN-LAST:event_GenerateFromPBVC0BtnMouseClicked

    public Project myLoadProjectFromFile(String sFilename){
        Collection errors = new ArrayList();
        return Project.loadProjectFromFile(sFilename,errors);
    }

    public String [] SparqlValues(String SPARQLTxtArea){
        String sSPARQL=SPARQLTxtArea.toLowerCase().trim();
        int iWhere=sSPARQL.indexOf("where");
        String sVariables=sSPARQL.substring(7,iWhere).trim().replace('?', '%');
        String []sVal=sVariables.split("%");
        return sVal;
    }

    public Instance CreatePlaceByReverseGeocoding (String sURI, String lat, String lon, String sTimestamp){
        Instance instanceResult=null;
        String [] results=new String[5];
        theLogger.info("Inside CreatePlaceByReverseGeocoding using Google, lat:"+lat+", lon:"+lon);
        try {
            //http://maps.google.com/maps/api/geocode/xml?latlng=-37.781094,145.02954&sensor=false
            String url = "http://maps.google.com/maps/api/geocode/xml?latlng=" + lat + "," + lon + "&sensor=false";
            HttpClient client = new HttpClient();
            GetMethod get = new GetMethod(url);
            int statusCode = client.executeMethod(get);
            if (statusCode != HttpStatus.SC_OK) {
                throw new RuntimeException(" Could not make HTTP  request properly: " + get.getStatusLine());
            }
            InputStream response = get.getResponseBodyAsStream();
            SAXReader reader = new SAXReader();
            Document document = reader.read(response);
            /*List list=document.selectNodes("//result");
            Iterator iter=list.iterator();
            while(iter.hasNext()){
                Element element=(Element)iter.next();
                Iterator iterator=element.elementIterator("formatted_address");
                while (iterator.hasNext()){
                    Element formattedAddressElement=(Element)iterator.next();                    
                }
            }*/
            List list = document.selectNodes("//result/address_component" );
            Iterator iter=list.iterator();
            String street_number="",route="", suburb="", postcode="", country="";
             while(iter.hasNext()){
             Element element=(Element)iter.next();
             
             String sLongname=element.elementText("long_name");
             String sType=element.elementText("type");

             if (sType.equals("street_number")){
                 if (sLongname.length()>0) street_number=sLongname;
                //System.out.println("Route name:"+route);
             }else if (sType.equals("route")){
                 if (sLongname.length()>0) route=sLongname;
                //System.out.println("Route name:"+route);
             }else if (sType.equals("postal_code")){
                 if (sLongname.length()>0) postcode=sLongname;
                 //System.out.println("post code:"+postcode);
             }else if (sType.equals("locality")){
                 if (sLongname.length()>0) suburb=sLongname;
                 //System.out.println("locality:"+suburb);
             }else if (sType.equals("country")){
                 if (sLongname.length()>0) country=sLongname;
                 //System.out.println("locality:"+suburb);
             }
              //while(iterator.hasNext()){
              //Element longElement=(Element)iterator.next();
              //System.out.println(longElement.getText().trim());
              //}
             }
             results[0]=street_number;
             results[1]=route;
             results[2]=suburb;
             results[3]=postcode;
             results[4]=country;

             theLogger.info("Number:"+street_number+", route:"+route+
                    ", suburb:"+suburb+", postcode:"+postcode+", country:"+country);
             instanceResult=CreatePlaceByAddress(sURI, street_number, route,
                     suburb,postcode,country, sTimestamp);

        } catch (DocumentException ex) {
            theLogger.severe(ex.toString());
        } catch (IOException ex) {
            theLogger.severe(ex.toString());
        } catch (Exception ex) {
            theLogger.severe(ex.toString());
        }
        return instanceResult;
    }

    public Instance CreatePlaceByAddress(String sURI, String street_number,
            String route, String suburb, String postcode, String country, String sTimestamp){
        Instance instanceToAddTo=null;
        // Create Instance for PostalAddress
        //http://www.tuannguyen.mobi/ontologies/2010/tinypbvc.owl#PostalAddress

        theLogger.info("Inside CreatePlaceByAddress");
        kb  = prj.getKnowledgeBase();
            
            String ssURI=sURI+"PostalAddress";
            Cls cPostalAddress =kb.getCls(ssURI);

            String streetNumberURI= sURI+"streetNumber";
            String streetNameURI= sURI+"streetName";
            String suburbURI= sURI+"suburb";
            String CountryURI= sURI+"Country";
            String postCodeURI= sURI+"postCode";
            String timestampURI= sURI+"timestamp";          
            String streetNumberVal= street_number;
             
            String streetNameVal= route;
            String suburbVal=  suburb;
            String CountryVal= country;
            String postCodeVal= postcode;
            String timestampVal=sTimestamp;


                 Date mdate=new Date();
                 String sTemp=streetNameVal.replace(" ","_");
                 String sInstanceName=sURI+sTemp+postCodeVal;
                 theLogger.info("Instance name:"+sInstanceName);

                 // Check wether Place is existed?
                  Instance myInstance=null;
                  boolean bInstanceExisted=false;
                    try {
                     myInstance= kb.getInstance(sInstanceName);
                        if (myInstance.isValid()){
                           theLogger.info("Instance is existed");
                           bInstanceExisted=true;
                        }
                     System.out.println(myInstance.getName());
                    }catch(Exception e){
                        bInstanceExisted=false;
                        theLogger.info("Instance Does NOT Valid");
                    }

                 if (bInstanceExisted) {
                     return myInstance;
                 }else {
                 // Create new instance
                 instanceToAddTo = cPostalAddress.createDirectInstance(sInstanceName);
                 Slot streetNumber_slot  = kb.getSlot(streetNumberURI);
                 Slot streetName_slot  = kb.getSlot(streetNameURI);
                 Slot suburb_slot  = kb.getSlot(suburbURI);
                 Slot postCode_slot= kb.getSlot(postCodeURI);
                 Slot Country_slot = kb.getSlot(CountryURI);
                 Slot timestamp_slot = kb.getSlot(timestampURI);

                 instanceToAddTo.setOwnSlotValue(streetNumber_slot, streetNumberVal);
                 instanceToAddTo.setOwnSlotValue(streetName_slot,streetNameVal);
                 instanceToAddTo.setOwnSlotValue(suburb_slot,suburbVal);
                 instanceToAddTo.setOwnSlotValue(postCode_slot, postCodeVal);
                 instanceToAddTo.setOwnSlotValue(Country_slot,CountryVal);
                 instanceToAddTo.setOwnSlotValue(timestamp_slot, timestampVal);
                 kb.addInstance(instanceToAddTo, "Place: "+sInstanceName+" added", cPostalAddress, true);
                 }

        return instanceToAddTo;
    }

    public boolean InsertInstance(float fLat, float  fLon, float  fAlt,
                                float  fSpeed, String sDate, String sTimestamp,
                                String sAddress, String sName, String sURI){
        boolean result = false;
            theLogger.info("InsertInstance");
            kb = prj.getKnowledgeBase();
            
            String ssURI = sURI + "Location";
            Cls cLocation = kb.getCls(ssURI);
            String sLatURI = sURI + "lat";
            String sLonURI = sURI + "lon";
            String sAltURI = sURI + "alt";
            String sSpeedURI = sURI + "speed";
            String sTimeURI = sURI + "timestamp";
            String sDateURI = sURI + "date";
            String sBtAddressURI = sURI + "btAddress";
            String sBtNameURI = sURI + "btName";
            String hasPostalAddressURI = "http://www.tuannguyen.mobi/ontologies/2010/tinypbvc.owl#hasPostalAddress";


            theLogger.info("Insert instance, creating new Postal Address for geocoding ");
            Instance placeInstance = CreatePlaceByReverseGeocoding (sURI,
                    Float.toString(fLat),Float.toString(fLon), sTimestamp);
            theLogger.info("Postal Address instance created");

            try {
                Date mdate = new Date();
                long lRandomNumber = mdate.getTime();
                String sInstanceName = ssURI + lRandomNumber;
                // Create new instance
                Instance instanceToAddTo = cLocation.createDirectInstance(sInstanceName);
                //instanceToAddTo.s
                //Thread.sleep(10);
                // Set relationship
                //Slot sFriendOfSlot= kb.getSlot("http://xmlns.com/foaf/0.1/friendOf");
                Slot lat_slot = kb.getSlot(sLatURI);
                Slot lon_slot = kb.getSlot(sLonURI);
                Slot alt_slot = kb.getSlot(sAltURI);
                Slot speed_slot = kb.getSlot(sSpeedURI);
                Slot date_slot = kb.getSlot(sDateURI);
                Slot timestamp_slot = kb.getSlot(sTimeURI);                
                Slot hasPostalAddress_slot = kb.getSlot(hasPostalAddressURI);

                instanceToAddTo.setOwnSlotValue(lat_slot, fLat);
                instanceToAddTo.setOwnSlotValue(lon_slot, fLon);
                instanceToAddTo.setOwnSlotValue(alt_slot, fAlt);
                instanceToAddTo.setOwnSlotValue(speed_slot, fSpeed);
                instanceToAddTo.setOwnSlotValue(date_slot, sDate);
                instanceToAddTo.setOwnSlotValue(timestamp_slot, sTimestamp);
                        
                instanceToAddTo.setOwnSlotValue(hasPostalAddress_slot, placeInstance);
                
                kb.addInstance(instanceToAddTo, "Location: " + sInstanceName + " added", cLocation, true);
                theLogger.info("Location instance created");

            } catch (Exception ex) {
                Logger.getLogger(BrowseKB.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        
        return result;
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                BrowseKB dialog = new BrowseKB(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AddOneInstanceBtn;
    private javax.swing.JButton AssertAvgSpeedBtn;
    private javax.swing.JTextField BasedDirTF;
    private javax.swing.JButton CheckExistedBtn;
    private javax.swing.JButton ConnectKnowledgeBaseBtn;
    private javax.swing.JButton CreateSingleLocationBtn;
    private javax.swing.JButton CreateSinglePlaceBtn;
    private javax.swing.JPasswordField DBPasswordTxtFld;
    private javax.swing.JTextField DBURLtxtFld;
    private javax.swing.JTextField DBusernameTxtFld;
    private javax.swing.JTextField DatasetFilenameTF;
    private javax.swing.JButton DeleteAllBtn;
    private javax.swing.JButton DeleteInstanceBtn;
    private javax.swing.JTextField DurationTF;
    private javax.swing.JButton ExitBtn;
    private javax.swing.JButton GenerateFromPBVC0Btn;
    private javax.swing.JButton GetSparqlResultBtn;
    private javax.swing.JButton ImportGPStoKBbtn;
    private javax.swing.JButton ImportRawContextToKB;
    private javax.swing.JTextField InstanceNameTF;
    private javax.swing.JTextArea JessRuleArea;
    private javax.swing.JTextField JessStringTF;
    private javax.swing.JButton JessTestBtn;
    private javax.swing.JButton LoadInstanceBtn;
    private javax.swing.JButton LoadProjectsBtn;
    private javax.swing.JTextArea LoggingTA;
    private javax.swing.JButton NextBtn;
    private javax.swing.JTextField ProjectsTF;
    private javax.swing.JButton SparqlBtn;
    private javax.swing.JTextArea SparqlTxtArea;
    private javax.swing.JTextField SpeedLimitTF;
    private javax.swing.JTextField avgSpeedTF;
    private javax.swing.JTextField instanceNameTxtFld;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField latTF;
    private java.awt.List list1;
    private java.awt.List list2;
    private javax.swing.JTextField lonTF;
    private javax.swing.JTextField tsTF;
    // End of variables declaration//GEN-END:variables

    private String DB_URL = "";
    private String DB_USER = "";
    private String DB_PASSWD = "";
    private String DB = "MySQL";

    private Project prj =null;
    private List  prjList =new ArrayList();
    private List  kbList =new ArrayList();
    private List  owlModelList =new ArrayList();

    private List  threadClassList  =new ArrayList();
    private List  threadList =new ArrayList();



    private KnowledgeBase kb  = null;
    private OWLModel owlModel =null;
    private int iPos =0;
    
    private static Logger theLogger =
	 Logger.getLogger(BrowseKB.class.getName());
    private static FileHandler fileTxt;
    private static FileHandler fileXML;

    private static SimpleFormatter formatterTxt;
    public float sAvg=0;
    //private static XMLFormatter formatterTxt;
}
